//
//  ReadPageView_Scrap.m
//  KidReading
//
//  Created by telen on 16/4/26.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "ReadPageView_Scrap.h"
#import "ConstDefine.h"

@implementation ReadPageView_Scrap
{
    TLScrapView* scrapview;
    UIImage* scrapScreenImage;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //
        _modyScrapRectList = [NSMutableArray new];
        _delScrapRectlList = [NSMutableArray new];
        _syncScrapRectList = [NSMutableArray new];
        //
        __weak ReadPageView_Scrap* wself = self;
        scrapview = [[TLScrapView alloc] initWithFrame:self.bounds];
        scrapview.didDelScrapRect = ^(ScrapRectView* screct){
            [wself didDelScrapRect:screct];
        };
        scrapview.didModyScrapRect = ^(ScrapRectView* screct){
            [wself didModyScrapRect:screct];
        };
        [self addSubview:scrapview];
    }
    return self;
}

- (void)setEditModel:(BOOL)editModel
{
    [super setEditModel:editModel];
    scrapview.canEdit = editModel;
    if (scrapview && editModel) {
        scrapview.hidden = YES;
        scrapScreenImage = [self.pageview tl_takePicture];
        scrapview.hidden = NO;
    }
}

- (void)didDelScrapRect:(ScrapRectView*)screct
{
    NSArray* arr = [NSArray arrayWithArray:self.modyScrapRectList];
    for (ScrapRectView* view in arr) {
        if (view == screct) {
            [self.modyScrapRectList removeObject:view];
            break;
        }
    }
    arr = [NSArray arrayWithArray:self.syncScrapRectList];
    for (ScrapRectView* view in arr) {
        if (view == screct) {
            [self.syncScrapRectList removeObject:view];
            break;
        }
    }
    if (screct.localPath) {
        [[NSFileManager defaultManager] removeItemAtPath:screct.localPath error:nil];
    }
    [self.delScrapRectlList addObject:screct];
}

- (void)didModyScrapRect:(ScrapRectView*)screct
{
    BOOL forNew = YES;
    for (ScrapRectView* view in self.modyScrapRectList) {
        if (view == screct) {
            forNew = NO;
            break;
        }
    }
    if (forNew) {
        [self.modyScrapRectList addObject:screct];
    }
}

#pragma mark-
- (NSURL *)scrapLocalSavePath
{
    NSFileManager* sharedFM = [NSFileManager defaultManager];
    NSArray* possibleURLs = [sharedFM URLsForDirectory:NSCachesDirectory
                                             inDomains:NSUserDomainMask];
    NSURL* appSupportDir = nil;
    NSURL* appDirectory = nil;

    if ([possibleURLs count] >= 1) {
        // Use the first directory (if multiple are returned)
        appSupportDir = [possibleURLs objectAtIndex:0];
    }
    if (appSupportDir) {
        appDirectory = [appSupportDir URLByAppendingPathComponent:@"ScrapLocal_Jpeg"];
    }
    
    if(![[NSFileManager defaultManager] fileExistsAtPath:appDirectory.path])
    {
        [[NSFileManager defaultManager] createDirectoryAtURL:appDirectory withIntermediateDirectories:YES attributes:nil error:nil];
        [appDirectory setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:nil];
    }
    
    return appDirectory;
}

- (void)cutPageFor:(ScrapRectView*)screct FromUImage:(UIImage*)image
{
    if (image && screct) {
        UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
        CGRect rect = screct.frame;
        rect.origin.x *= scrapScreenImage.scale;
        rect.origin.y *= scrapScreenImage.scale;
        rect.size.width *= scrapScreenImage.scale;
        rect.size.height *= scrapScreenImage.scale;
        UIImage* img = [image croppedImage:rect];
        //
        long long cttime = [DataProcessing timestampFromNSDate:screct.createTime];
        NSString* name = [NSString stringWithFormat:@"scrap_%@_%@_%@_%@.jpg",@(uinfo.uid),@(self.pageview.bookid),@(self.pageview.pageIndex),@(cttime)];
        NSURL* directPath = [self scrapLocalSavePath];
        NSString *imageFilePath = [directPath.path stringByAppendingPathComponent:name];
        if([UIImageJPEGRepresentation(img, 0.66f) writeToFile:imageFilePath atomically:YES])//写入文件
        {
            screct.localPath = imageFilePath;
        }
    }
}

#pragma mark-
- (void)clearSyncScrapRects
{
    [_syncScrapRectList enumerateObjectsUsingBlock:^(ScrapRectView*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [scrapview removeScrapRect:obj];
    }];
    [_syncScrapRectList removeAllObjects];
}
- (ScrapRectView*)addScrapRectWithRect:(CGRect)frame filePath:(NSString*)urlPath localPath:(NSString*)localPath creatTime:(NSDate*)cttime modyTime:(NSDate*)mdtime
{
    return [scrapview addScrapRectWithRect:frame filePath:urlPath localPath:localPath creatTime:cttime modyTime:mdtime];
}
- (void)cutImageForModyScrapRect
{
    if (scrapScreenImage) {
        for (ScrapRectView* screct in _modyScrapRectList) {
            [self cutPageFor:screct FromUImage:scrapScreenImage];
        }
    }
}

@end
